package com.lintf.devdemo.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lintf.devdemo.common.Result;
import com.lintf.devdemo.dao.ISysFileInfoMapper;
import com.lintf.devdemo.entity.po.ISysFileInfo;
import com.lintf.devdemo.service.ISysFileInfoService;
import com.lintf.devdemo.service.ISysImageService;
import com.lintf.devdemo.utils.Base64;
import com.lintf.devdemo.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * @ system:Window
 * @ author:lin tingfeng
 * @ data:2022/10/19-14:17
 * @ package_name:com.lintf.devdemo.service.Impl
 * @ project_name:DevDemo
 * @ desc:图片文件处理逻辑实现
 */
@Service
@Transactional
public class ISysImageServiceImpl implements ISysImageService {

    @Value("${file.upload.path}")
    private String fileUploadPath;

    @Value("${show.image.base.url}")
    private String SHOW_IMAGE_BASE_URL;

    @Autowired
    private ISysFileInfoMapper iSysFileInfoMapper;

    @Autowired
    private ISysFileInfoService iSysFileInfoService;



    /**
     * 上传图片文件
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @Override
    public String uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        if (!this.fileUploadPath.endsWith("/")) {
            this.fileUploadPath = this.fileUploadPath + "/";
        }

        String folderPath = FileUtil.getFolderPath(this.fileUploadPath, new Date());
        String fileFullPath = "";
        List<MultipartFile> files = multipartRequest.getFiles("afiles");

        for (int i = 0; i < files.size(); ++i) {
            ISysFileInfo iSysFileInfo = FileUtil.ajaxUplod((MultipartFile) files.get(i), folderPath);
            String fileId = UUID.randomUUID().toString();
            if (i < files.size() - 1) {
                fileFullPath = fileFullPath + this.SHOW_IMAGE_BASE_URL + fileId + ",";
            } else {
                fileFullPath = fileFullPath + this.SHOW_IMAGE_BASE_URL + fileId;
            }

            iSysFileInfo.setId(fileId);
            iSysFileInfo.setUploadPerson("admin");
            iSysFileInfo.setUploadPersonId(UUID.randomUUID().toString());
            iSysFileInfo.setUploadTime(LocalDateTime.now());
            iSysFileInfoMapper.insert(iSysFileInfo);
        }
        return fileFullPath;
    }

    /**
     * 上传头像图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public Result uploadHeadImage(MultipartHttpServletRequest file) throws Exception {
        //校验上传文件的个数
        Iterator<String> iter = file.getFileNames();
        int count = 0;
        String fileName = null;
        while (iter.hasNext()) {
            fileName = iter.next();
            count++;
        }
        if (count > 1) {
            throw new Exception("每次只能上传一个文件");
        }
        if (StringUtils.isNotBlank(fileName)) {
            List<MultipartFile> files = file.getFiles(fileName);
            if (null != files && files.size() > 1) {
                throw new Exception("每次只能上传一个文件");
            }
        }
        String refId = UUID.randomUUID().toString().replaceAll("-", "");
        List<ISysFileInfo> fileInfos = iSysFileInfoService.uploadCompress(file, refId, "unit_person", "headImage", 100);
        if (null == fileInfos || fileInfos.size() < 1) {
            throw new Exception("上传头像失败");
        }
        ISysFileInfo fileInfo = fileInfos.get(0);
        return Result.success(fileInfo.getId(), "上传成功");
    }

    /**
     * 图片展示
     * @param id
     * @return
     */
    @Override
    public String showImgStream(String id) {
        ISysFileInfo iSysFileInfo = iSysFileInfoMapper.selectById(id);
        if (iSysFileInfo == null) {
            try {
                throw new Exception("文件不存在！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String readImageInputStream = Base64.readImageInputStream(iSysFileInfo.getFileLocation()).replaceAll("\n", "").replaceAll("\r", "");
        return readImageInputStream;
    }
}
